<template>
  <view class="page-container">
    <scroll-view scroll-y class="form-scroll">
      <!-- 门店图片轮播 -->
      <view class="image-section" v-if="!isEditing && storeData.id">
        <swiper class="store-swiper" indicator-dots circular>
          <swiper-item v-for="(image, index) in bannerImages" :key="index">
            <image :src="image" mode="aspectFill" class="swiper-image"></image>
          </swiper-item>
        </swiper>
        <view class="image-overlay">
          <view class="back-btn" @click="goBack">
            <uni-icons type="back" size="20" color="#fff"></uni-icons>
          </view>
          <view class="edit-btn" @click="toggleEdit">
            <uni-icons type="compose" size="20" color="#fff"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 统计数据卡片 -->
      <view class="stats-section" v-if="!isEditing && storeData.id">
        <view class="stats-grid">
          <view class="stat-item">
            <text class="stat-number">{{ statsData.venueCount || 0 }}</text>
            <text class="stat-label">场地数量</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ statsData.todayBookings || 0 }}</text>
            <text class="stat-label">今日预订</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ statsData.activeVenues || 0 }}</text>
            <text class="stat-label">可用场地</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ (statsData.utilizationRate || 0).toFixed(1) }}%</text>
            <text class="stat-label">使用率</text>
          </view>
        </view>
      </view>

      <!-- 快速操作按钮 -->
      <view class="quick-actions" v-if="!isEditing && storeData.id">
        <view class="action-grid">
          <view class="action-item" @click="navigateToVenues">
            <uni-icons type="home" size="24" color="var(--primary-color)"></uni-icons>
            <text class="action-label">场地管理</text>
          </view>
          <view class="action-item" @click="navigateToBookings">
            <uni-icons type="calendar" size="24" color="var(--primary-color)"></uni-icons>
            <text class="action-label">预订管理</text>
          </view>
          <view class="action-item" @click="navigateToSettings">
            <uni-icons type="gear" size="24" color="var(--primary-color)"></uni-icons>
            <text class="action-label">营业设置</text>
          </view>
          <view class="action-item" @click="showQRCode">
            <uni-icons type="scan" size="24" color="var(--primary-color)"></uni-icons>
            <text class="action-label">门店码</text>
          </view>
        </view>
      </view>

      <!-- 表单内容 -->
      <uni-forms ref="formRef" :modelValue="formData" :rules="rules" label-width="80px" label-align="right">
        <uni-card title="基本信息" :is-shadow="true">
          <uni-forms-item label="门店名称" name="name" required>
            <uni-easyinput 
              v-model="formData.name" 
              placeholder="请输入门店名称" 
              :disabled="!isEditing"
            />
          </uni-forms-item>
          <uni-forms-item label="所在城市" name="city_id" required>
            <uni-data-select 
              v-model="formData.city_id" 
              :localdata="cityOptions" 
              placeholder="请选择城市"
              :disabled="!isEditing"
            ></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="详细地址" name="address" required>
            <uni-easyinput 
              v-model="formData.address" 
              placeholder="请输入详细地址" 
              :disabled="!isEditing"
            />
          </uni-forms-item>
          <uni-forms-item label="联系人" name="contact_person" required>
            <uni-easyinput 
              v-model="formData.contact_person" 
              placeholder="请输入联系人" 
              :disabled="!isEditing"
            />
          </uni-forms-item>
          <uni-forms-item label="联系电话" name="phone" required>
            <uni-easyinput 
              v-model="formData.phone" 
              placeholder="请输入联系电话" 
              :disabled="!isEditing"
            />
          </uni-forms-item>
          <uni-forms-item label="营业状态" name="status" required>
            <uni-data-select 
              v-model="formData.status" 
              :localdata="statusOptions"
              :disabled="!isEditing"
            ></uni-data-select>
          </uni-forms-item>
        </uni-card>

        <uni-card title="营业时间" :is-shadow="true" v-if="isEditing || formData.business_hours">
          <uni-forms-item label="营业时间" name="business_hours">
            <business-hours-editor 
              v-model="formData.business_hours" 
              :disabled="!isEditing"
            />
          </uni-forms-item>
        </uni-card>

        <uni-card title="门店描述" :is-shadow="true" v-if="isEditing || formData.description">
          <uni-forms-item label="门店描述" name="description">
            <uni-easyinput 
              v-model="formData.description" 
              type="textarea" 
              placeholder="请输入门店描述"
              :disabled="!isEditing"
            />
          </uni-forms-item>
          <uni-forms-item label="特别通知" name="notice">
            <uni-easyinput 
              v-model="formData.notice" 
              type="textarea" 
              placeholder="请输入特别通知"
              :disabled="!isEditing"
            />
          </uni-forms-item>
        </uni-card>

        <uni-card title="门店设施" :is-shadow="true" v-if="isEditing || facilitiesList.length > 0">
          <uni-forms-item label="设施配置" name="facilities">
            <facility-editor 
              v-model="facilitiesList" 
              :disabled="!isEditing"
            />
          </uni-forms-item>
        </uni-card>

        <uni-card title="门店图片" :is-shadow="true" v-if="isEditing">
          <uni-forms-item label="主图" name="images" required>
            <uni-file-picker
              v-model="imageFiles"
              file-mediatype="image"
              mode="grid"
              :limit="1"
              @select="handleImageUpload"
              @delete="handleImageDelete"
              :auto-upload="false"
            />
          </uni-forms-item>
          <uni-forms-item label="轮播图" name="banner">
             <uni-file-picker
              v-model="bannerFiles"
              file-mediatype="image"
              mode="grid"
              :limit="5"
              @select="handleBannerUpload"
              @delete="handleBannerDelete"
              :auto-upload="false"
            />
          </uni-forms-item>
        </uni-card>
      </uni-forms>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions safe-area-inset-bottom">
      <button v-if="!isEditing && storeData.id" class="edit-btn-footer" @click="toggleEdit">
        编辑门店
      </button>
      <template v-else>
        <button class="cancel-btn" @click="handleCancel">取消</button>
        <button class="submit-btn" @click="handleSubmit">{{ storeData.id ? '保存' : '创建' }}</button>
      </template>
    </view>

    <!-- 二维码弹窗 -->
    <uni-popup ref="qrPopup" type="center">
      <view class="qr-modal">
        <view class="qr-header">
          <text class="qr-title">门店二维码</text>
          <uni-icons type="close" size="20" @click="closeQRCode"></uni-icons>
        </view>
        <view class="qr-content">
          <canvas canvas-id="qrCanvas" class="qr-canvas"></canvas>
          <text class="qr-desc">客户扫码可直接查看门店信息</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { fetchStoreDetail, createStore, updateStore, fetchCities, fetchStoreStats } from '@/api/store';
import type { Store, City } from '@/types/store';
import BusinessHoursEditor from './components/BusinessHoursEditor.vue';
import FacilityEditor from './components/FacilityEditor.vue';

const formRef = ref<any>(null);
const qrPopup = ref<any>(null);
const isEditing = ref(false);
const storeData = ref<Partial<Store>>({});

const formData = reactive<Partial<Store>>({
  name: '',
  city_id: undefined,
  address: '',
  contact_person: '',
  phone: '',
  status: 1,
  business_hours: '',
  description: '',
  notice: '',
  images: '',
  banner: '',
  facilities: '',
});

const rules = {
  name: { rules: [{ required: true, errorMessage: '请输入门店名称' }] },
  city_id: { rules: [{ required: true, errorMessage: '请选择城市' }] },
  address: { rules: [{ required: true, errorMessage: '请输入详细地址' }] },
  contact_person: { rules: [{ required: true, errorMessage: '请输入联系人' }] },
  phone: { rules: [{ required: true, errorMessage: '请输入联系电话' }] },
  status: { rules: [{ required: true, errorMessage: '请选择营业状态' }] },
  images: { rules: [{ required: true, errorMessage: '请上传主图' }] },
};

const cityOptions = ref<{ value: number; text: string }[]>([]);
const statusOptions = [
  { value: 1, text: '营业中' },
  { value: 0, text: '休息中' },
];

const imageFiles = ref<any[]>([]);
const bannerFiles = ref<any[]>([]);
const facilitiesList = ref<string[]>([]);
const statsData = ref<any>({});

const pageTitle = ref('新增门店');
const storeId = ref<number | null>(null);

// 计算轮播图片列表
const bannerImages = computed(() => {
  const images = [];
  if (storeData.value.images) {
    images.push(storeData.value.images);
  }
  if (storeData.value.banner) {
    try {
      const bannerList = JSON.parse(storeData.value.banner);
      if (Array.isArray(bannerList)) {
        images.push(...bannerList);
      }
    } catch (error) {
      console.error('解析轮播图失败:', error);
    }
  }
  return images.length > 0 ? images : ['/static/images/store-placeholder.png'];
});

// 文件上传
const uploadFile = (file: any): Promise<string> => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: '/api/v1/upload',
      filePath: file.tempFilePath,
      name: 'file',
      success: (uploadRes) => {
        const data = JSON.parse(uploadRes.data);
        if (data.success) {
          resolve(data.data);
        } else {
          reject(new Error(data.message || '上传失败'));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

const handleImageUpload = async (e: any) => {
  try {
    const url = await uploadFile(e.tempFiles[0]);
    formData.images = url;
    imageFiles.value = [{ url }];
  } catch (error: any) {
    uni.showToast({ title: error.message || '主图上传失败', icon: 'none' });
  }
};

const handleImageDelete = () => {
  formData.images = '';
  imageFiles.value = [];
};

const handleBannerUpload = async (e: any) => {
  try {
    const urls = await Promise.all(e.tempFiles.map((file: any) => uploadFile(file)));
    const newBanners = urls.map(url => ({ url }));
    bannerFiles.value.push(...newBanners);
    const allUrls = bannerFiles.value.map(f => f.url);
    formData.banner = JSON.stringify(allUrls);
  } catch (error: any) {
    uni.showToast({ title: error.message || '轮播图上传失败', icon: 'none' });
  }
};

const handleBannerDelete = (e: any) => {
  const deletedUrl = e.tempFilePath;
  bannerFiles.value = bannerFiles.value.filter(f => f.url !== deletedUrl);
  const allUrls = bannerFiles.value.map(f => f.url);
  formData.banner = JSON.stringify(allUrls);
};

// 切换编辑模式
const toggleEdit = () => {
  isEditing.value = !isEditing.value;
  if (isEditing.value) {
    // 进入编辑模式，复制数据
    Object.assign(formData, storeData.value);
    setupEditData();
  }
};

// 设置编辑数据
const setupEditData = () => {
  // 设置图片
  if (storeData.value.images) {
    imageFiles.value = [{ url: storeData.value.images }];
  }
  
  // 设置轮播图
  if (storeData.value.banner) {
    try {
      const bannerList = JSON.parse(storeData.value.banner);
      if (Array.isArray(bannerList)) {
        bannerFiles.value = bannerList.map(url => ({ url }));
      }
    } catch (error) {
      console.error('解析轮播图失败:', error);
    }
  }
  
  // 设置设施
  if (storeData.value.facilities) {
    try {
      const facilities = JSON.parse(storeData.value.facilities);
      if (Array.isArray(facilities)) {
        facilitiesList.value = facilities;
      }
    } catch (error) {
      console.error('解析设施失败:', error);
    }
  }
};

// 监听设施变化
watch(facilitiesList, (newVal) => {
  formData.facilities = JSON.stringify(newVal);
}, { deep: true });

const handleCancel = () => {
  if (storeData.value.id) {
    isEditing.value = false;
    // 恢复原始数据
    Object.assign(formData, storeData.value);
    setupEditData();
  } else {
    goBack();
  }
};

const handleSubmit = () => {
  formRef.value.validate().then(async () => {
    try {
      uni.showLoading({ title: '保存中...' });
      
      if (storeId.value) {
        await updateStore(storeId.value, formData as Store);
        uni.showToast({ title: '更新成功' });
        // 更新本地数据
        Object.assign(storeData.value, formData);
        isEditing.value = false;
      } else {
        const result = await createStore(formData as Store);
        uni.showToast({ title: '创建成功' });
        setTimeout(() => {
          uni.redirectTo({ url: `/pages/stores/detail?id=${result.id}` });
        }, 1500);
      }
    } catch (error: any) {
      uni.showToast({ title: error.message || '操作失败', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  }).catch((err: any) => {
    console.log('表单校验失败', err);
  });
};

const goBack = () => {
  uni.navigateBack();
};

// 导航到场地管理
const navigateToVenues = () => {
  uni.navigateTo({ url: `/pages/venues/index?storeId=${storeId.value}` });
};

// 导航到预订管理
const navigateToBookings = () => {
  uni.navigateTo({ url: `/pages/bookings/index?storeId=${storeId.value}` });
};

// 导航到设置
const navigateToSettings = () => {
  uni.navigateTo({ url: `/pages/stores/settings?id=${storeId.value}` });
};

// 显示二维码
const showQRCode = () => {
  qrPopup.value?.open();
  generateQRCode();
};

// 关闭二维码
const closeQRCode = () => {
  qrPopup.value?.close();
};

// 生成二维码
const generateQRCode = () => {
  // 这里可以集成二维码生成库
  const ctx = uni.createCanvasContext('qrCanvas');
  ctx.setFillStyle('#000000');
  ctx.fillRect(0, 0, 200, 200);
  ctx.draw();
};

// 获取城市列表
const getCities = async () => {
  try {
    const res = await fetchCities();
    cityOptions.value = res.list.map((city: City) => ({ 
      value: city.id, 
      text: city.name 
    }));
  } catch (error) {
    console.error('获取城市列表失败:', error);
  }
};

// 获取门店统计数据
const getStoreStats = async () => {
  if (!storeId.value) return;
  
  try {
    const res = await fetchStoreStats(storeId.value);
    statsData.value = res;
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

onLoad(async (options: any) => {
  await getCities();
  
  if (options.id) {
    storeId.value = Number(options.id);
    pageTitle.value = '门店详情';
    uni.setNavigationBarTitle({ title: pageTitle.value });
    
    try {
      const res = await fetchStoreDetail(storeId.value);
      storeData.value = res;
      Object.assign(formData, res);
      setupEditData();
      getStoreStats();
    } catch (error) {
      uni.showToast({ title: '获取门店详情失败', icon: 'none' });
    }
  } else {
    isEditing.value = true;
    uni.setNavigationBarTitle({ title: pageTitle.value });
  }
});

onShow(() => {
  if (storeId.value) {
    getStoreStats();
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.form-scroll {
  flex: 1;
  height: 0;
  padding-bottom: 80px;
}

.image-section {
  position: relative;
  height: 200px;
}

.store-swiper {
  width: 100%;
  height: 100%;
}

.swiper-image {
  width: 100%;
  height: 100%;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: linear-gradient(to bottom, rgba(0,0,0,0.5), transparent);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
}

.back-btn, .edit-btn {
  width: 36px;
  height: 36px;
  border-radius: 18px;
  background-color: rgba(0,0,0,0.3);
  display: flex;
  justify-content: center;
  align-items: center;
}

.stats-section {
  margin: 10px;
  background-color: #fff;
  border-radius: var(--border-radius);
  padding: 20px;
  box-shadow: var(--shadow);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: var(--primary-color);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--text-color-secondary);
}

.quick-actions {
  margin: 10px;
  background-color: #fff;
  border-radius: var(--border-radius);
  padding: 20px;
  box-shadow: var(--shadow);
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 10px;
}

.action-label {
  font-size: 12px;
  color: var(--text-color);
  margin-top: 8px;
}

.uni-card {
  margin: 10px !important;
}

.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 20px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
  display: flex;
  gap: 10px;
}

.edit-btn-footer {
  width: 100%;
  height: 44px;
  line-height: 44px;
  background-color: var(--primary-color);
  color: #fff;
  border-radius: var(--border-radius);
  font-size: 16px;
}

.cancel-btn, .submit-btn {
  flex: 1;
  height: 44px;
  border-radius: var(--border-radius);
  font-size: 16px;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.submit-btn {
  background-color: var(--primary-color);
  color: #fff;
}

.qr-modal {
  background-color: #fff;
  border-radius: var(--border-radius);
  padding: 20px;
  width: 280px;
}

.qr-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.qr-title {
  font-size: 18px;
  font-weight: bold;
}

.qr-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qr-canvas {
  width: 200px;
  height: 200px;
  border: 1px solid #eee;
  margin-bottom: 10px;
}

.qr-desc {
  font-size: 14px;
  color: var(--text-color-secondary);
  text-align: center;
}
</style>